package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.sharedmobility.dao.TripDAO;
import com.sharedmobility.dao.VehicleDAO;
import com.sharedmobility.model.Trip;
import com.sharedmobility.model.Vehicle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Map;
import java.util.HashMap;

@WebServlet("/api/rent")
public class RentServlet extends HttpServlet {
    private VehicleDAO vehicleDAO;
    private TripDAO tripDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        vehicleDAO = new VehicleDAO();
        tripDAO = new TripDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取当前登录用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取请求参数
            Map<String, Object> requestData = gson.fromJson(request.getReader(), Map.class);
            Integer vehicleId = ((Number) requestData.get("vehicleId")).intValue();
            String startLocation = (String) requestData.get("startLocation");

            // 检查车辆是否可用
            Vehicle vehicle = vehicleDAO.findById(vehicleId);
            if (vehicle == null) {
                throw new Exception("车辆不存在");
            }
            if (vehicle.getStatus() != 1) {
                throw new Exception("车辆不可用");
            }

            // 创建行程
            Trip trip = new Trip();
            trip.setUserId(userId);
            trip.setVehicleId(vehicleId);
            trip.setStartTime(new Timestamp(System.currentTimeMillis()));
            trip.setStartLocation(startLocation);
            trip.setStatus(1); // 1表示进行中

            boolean success = tripDAO.create(trip);
            if (!success) {
                throw new Exception("创建行程失败");
            }

            // 更新车辆状态
            vehicle.setStatus(2); // 2表示使用中
            vehicleDAO.update(vehicle);

            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "租借成功");
            result.put("data", trip);
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 